<!-- 已收费项目 -->
<template>
  <div>
    <el-row class="mt10 spn" type="flex">
      <Search :data="selections" :attribute="'createdTime'" @dateChange="handleDateChange" @change="handleTypeChange" />
      <el-form ref="searchFormRef" :model="searchForm" label-width="80px" :inline="true">
        <el-form-item>
          <el-input v-model="searchForm.customerName" class="inputCss" placeholder="姓名、手机号、会员号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchBtn">搜索顾客</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <!-- 表单区域 -->
    <el-table v-loading="loading" :data="chargeList">
      <el-table-column label="名称" prop="projectName" />
      <!-- <el-table-column label="项目属性" prop="productAttrib" /> -->
      <el-table-column label="项目单号" prop="productNo" align="center" />
      <el-table-column label="订单号" prop="orderCode" align="center" />
      <el-table-column label="顾客" prop="customerName" align="center" />
      <el-table-column label="收费时间" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.collectionTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="120" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="openPrescriptionBtn(scope.row)">开处方</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :page-num="params.page" :page-size="params.pageSize" :on-change="handlePaginationChange" :total="total" />
    <!-- 开处方 -->
    <Dialog :title="title" :visible.sync="visible" :button-text="testBtn" :loading="loading" @close="handleClose" @confirm="submitForm">
      <p class="ps"><strong>顾客</strong></p>
      <div class="headStyle">
        <span>名称：{{ chargeData.customerName }}</span><span>性别：{{ chargeData.sex }}</span><span>年龄：{{ chargeData.age }}</span><span>项目：{{ chargeData.projectName }}</span>
      </div>
      <p class="ps pTwo">
        <span><strong>处方</strong></span><span>
          <el-button class="addBtnCss" @click="addDrugBtn">增加药品</el-button>
        </span>
      </p>
      <el-table v-loading="loading" :data="chargeTableData">
        <el-table-column label="名称" prop="medicinesName" />
        <el-table-column label="规格" prop="medicinesSpec" />
        <el-table-column label="单位" prop="medicinesUnit" />
        <el-table-column v-if="flag" label="用法" min-width="100px" align="center">
          <template slot-scope="scope">
            <dictionary-selector code="swan_department_ypyf" :value.sync="scope.row.usageMethod" />
          </template>
        </el-table-column>
        <el-table-column v-if="flag" label="频率" min-width="100px" align="center">
          <template slot-scope="scope">
            <dictionary-selector code="swan_department_ypsypl" :value.sync="scope.row.frequency" />
          </template>
        </el-table-column>
        <el-table-column label="单价" prop="price" align="center" />
        <el-table-column label="可用库存" prop="availableStock" align="center" />
        <el-table-column label="开单数量" min-width="100px" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.quantity" controls-position="right" :min="1" style="width: 80px;" @change="quantityChange" />
          </template>
        </el-table-column>
        <!-- <el-table-column v-if="flag" label="总价" prop="zongjia" /> -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="deleteBtn(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-form ref="requestFromRef" :model="requestInfo" :rules="requestFromRules">
        <el-form-item prop="amount">
          <span class="pTwo">
            <span>
              <strong>合计：￥{{ requestInfo.amount?requestInfo.amount:0 }}</strong>
            </span>
          </span>
        </el-form-item>
        <el-form-item :prop="flag?'medicalAdvice':''">
          <span v-if="flag">
            <span><strong>医嘱：</strong></span>
            <el-input v-model="requestInfo.medicalAdvice" type="textarea" :autosize="{ minRows:4}" placeholder="请输入内容" class="textareaCss" />
          </span>
        </el-form-item>
      </el-form>
    </Dialog>
    <!-- 添加药品 -->
    <Dialog :title="titleTwo" :visible.sync="visibleTwo" :button-text="testBtnTwo" :loading="loading" @close="handleClose" @confirm="submitFormTwo">
      <el-form ref="ruleForm" :inline="true" :model="formInline" size="mini">
        <!-- <span>
          <el-form-item>
            <el-cascader v-model="formInline.quanbu" :options="optionsos" :props="{checkStrictly:true,children: 'childList',value: 'id',label: 'name', }" clearable @change="handleCascader" />
          </el-form-item>
        </span> -->
        <span class="plusCustomer">
          <el-form-item>
            <el-input v-model="formInline.name" placeholder="请输入名称或拼音码" clearable />
          </el-form-item>
          <el-form-item>
            <el-button @click="onSubmit">搜索</el-button>
          </el-form-item>
        </span>
      </el-form>
      <el-table v-loading="loading" :data="addDrugList" @selection-change="handleSelection">
        <el-table-column type="selection" width="55" />
        <el-table-column label="编号" prop="no" />
        <el-table-column label="名称" prop="name" align="center" />
        <el-table-column label="规格" prop="spec" align="center" />
        <el-table-column label="单位" prop="unit" align="center" />
        <!-- <el-table-column label="描述" prop="remark" align="center" /> -->
        <el-table-column label="销售价格" prop="sellPrice" align="center" />
        <el-table-column label="剩余库存" prop="inventoryFloor" align="center" />
      </el-table>
      <pagination :page-num="paramsTwo.page" :page-size="paramsTwo.pageSize" :on-change="handlePaginationChangeTwo" :total="totalTwo" />
    </Dialog>
  </div>
</template>
<script>
import { DictionarySelector } from "@rabbit.do/rabbit";
// import { TypeSelection } from "@monkey.do/monkey";
import Search from "@/components/Search";
import { selections } from "@/config";
import Dialog from "@/components/Dialog/index";
export default {
  components: {
    // TypeSelection,
    DictionarySelector,
    Search,
    Dialog,
  },
  data() {
    return {
      selections,
      searchForm: {
        paymentStatus: '已收款',
      },
      options: [],
      params: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      total: 0,
      paramsTwo: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      totalTwo: 0,
      chargeList: [],
      chargeData: {},
      optionsos: [],
      chargeTableData: [],
      formInline: {
        type: '药品',
      },
      addDrugList: [],
      addDrugArr: [], // 添加药品选中数据
      requestInfo: {
        amount: 0,
        medicalAdvice: '',
      },
      type: 2, // 类型 1-项目、2-处方、3-物料
      title: "",
      visible: false,
      testBtn: "",
      titleTwo: "",
      visibleTwo: false,
      testBtnTwo: "",
      loading: false,
      flag: false,
      requestFromRules: {
        amount: [
          { required: true, message: '请输入会员折扣', trigger: ['blur', 'change'] },
        ],
        medicalAdvice: [
          { required: true, message: '请输入医嘱', trigger: 'blur' },
        ],
      },
    };
  },
  created() {
    this.getChargeList();
  },
  methods: {
    // async getChargeList() {
    //   this.loading = true;
    //   const res = await this.$api['department/order/orderlist']({ ...this.params, query: this.searchForm });
    //   this.loading = false;
    //   if (res.code !== 200) return this.$message.error('查询治疗项目列表失败！');
    //   this.chargeList = res.data.result;
    //   this.total = res.data.total;
    // },
    handlePaginationChange(val) {
      this.params = { page: val.pageNum, pageSize: val.pageSize };
      this.getChargeList();
    },
    // 搜索
    searchBtn() {
      this.getChargeList();
    },
    // 开处方
    async openPrescriptionBtn(row) {
      // console.log(row.customerName);
      this.title = "开处方单";
      this.testBtn = "开单";
      this.flag = true;
      this.visible = true;
      const res = await this.$api['department/order/customer']({ name: row.customerName });
      // console.log(res);
      if (res.code === 200 && res.data) {
        this.chargeData = Object.assign(row, res.data);
      } else {
        this.chargeData = row;
      }
    },
    // 开单
    async submitForm() {
      this.chargeData.name = this.chargeData.projectName;
      this.loading = true;
      const res = await this.$api['department/order/addprescriptionlist']({ prescriptionListDetailsDtoList: this.chargeTableData, ...this.chargeData, ...this.requestInfo, drawer: this.$store.getters.currentUserInfo.name });
      this.loading = false;
      // console.log(res);
      if (res.code !== 200) return this.$message.error('开单失败！');
      this.$message.success('开单成功！');
      this.visible = false;
    },
    // 获取药品列表
    async getMedicines() {
      this.loading = true;
      const res = await this.$api['department/order/medicines']({ ...this.paramsTwo, query: this.formInline });
      this.loading = false;
      if (res.code !== 200) return this.$message.error('获取药品列表失败！');
      this.addDrugList = res.data.result;
      this.totalTwo = res.data.total;
    },
    // 开单数量变化
    quantityChange(val) {
      this.requestInfo.amount = 0;
      this.chargeTableData.map(item => {
        this.requestInfo.amount += item.price * item.quantity;
      });
    },
    // 增加药品
    addDrugBtn() {
      this.titleTwo = "增加药品";
      this.testBtnTwo = "已选择";
      this.flag = true;
      this.visibleTwo = true;
      this.getMedicines();
      // this.addDrug();
    },
    handlePaginationChangeTwo(val) {
      this.paramsTwo = { page: val.pageNum, pageSize: val.pageSize };
      this.addDrugBtn();
    },
    // 添加药品-搜索
    onSubmit() {
      this.getMedicines();
    },
    // 产品-药品列表
    addDrug() {
      // addDrugList(this.params).then(res => {
      //   if (res.statusCode === 600) {
      //     this.addDrugList = res.data;
      //   }
      // });
    },
    // 产品-物料列表
    addMaterial() {
      // addMaterialList(this.params).then(res => {
      //   if (res.statusCode === 600) {
      //     this.addDrugList = res.data;
      //   }
      // });
    },
    // 监听分类选中的值
    handleCascader(val) {
      // console.log(val);
      const bId = val.pop();
      this.params.bcatalogId = Number(bId);
      if (this.flag) {
        this.addDrug();
      } else {
        this.addMaterial();
      }
    },
    handleSelection(val) {
      this.addDrugArr = val;
    },
    // 删除
    async deleteBtn(row) {
      console.log(row, 'row');
      const confirmResult = await this.$confirm('请确认是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      }
      // const res = await this.$api['department/order/deleteprescriptionlist']({ id: row.id });
      // if (res.code !== 200) return this.$message.error('删除处方失败！');
      for (var i = 0; i < this.chargeTableData.length; i++) {
        if (this.chargeTableData[i].id === row.id) {
          this.chargeTableData.splice(i, 1);
        }
      }
      this.quantityChange();
      this.$message.success('删除处方成功！');
    },
    submitFormTwo() {
      this.chargeTableData.push(...this.addDrugArr);
      this.requestInfo.totalPrices = 0;
      this.chargeTableData.filter(item => {
        item.medicinesName = item.name; // 药品名称
        item.medicinesSpec = item.spec; // 药品规格
        item.medicinesUnit = item.unit;// 药品单位
        item.prescriptionListId = item.productClassificationId; // 处方单id
        item.price = item.sellPrice; // 单价
        item.availableStock = item.inventoryFloor; // 可用库存
        item.materialMedicineId = item.id;
        // item.amount = item.name; // 折扣
        // if (item.quantity === undefined) {
        //   item.quantity = 1;
        // }
        // this.requestInfo.totalPrices += Number(item.sellPrice);
      });
      // console.log(this.chargeTableData, '123');
      this.addDrugArr = [];
      this.visibleTwo = false;
    },
    // 关闭
    handleClose() {
      if (this.visible) {
        // this.$refs.ruleForm.resetFields();
      } else {
        this.chargeTableData = [];
        this.requestInfo = {};
        // this.$refs.requestFromRef.resetFields();
      }
    },
    // 顶部时间筛选
    handleDateChange(val) {
      this.searchForm.timeType = val.timeType;
      this.searchForm.createdTime = val.createdTime;
      this.getChargeList();
    },
    handleTypeChange(val) {
      this.searchForm.timeType = val.timeType;
      this.searchForm.createdTime = val.createdTime;
      this.getChargeList();
    },
  },
};
</script>
<style lang="scss" scoped>
.plusCustomer {
  float: right;
  margin-right: 30px;
}
</style>
